import {Row, Col, Button, Icon, message, Modal, Progress} from 'antd';
// import Row from '../../_antd1.11.2/row'
// import Col from '../../_antd1.11.2/col'
// import Button from '../../_antd1.11.2/button'
// import Icon from '../../_antd1.11.2/icon'
// import message from '../../_antd1.11.2/message'
// import Modal from '../../_antd1.11.2/modal';
// import Progress from '../../_antd1.11.2/progress';
import isEqual from 'lodash/isEqual';
import classNames from 'classnames'

const confirm = Modal.confirm;

import plupload from 'plupload'
//全局没有问题，打包会 flash 初始化加载会失败 dom 节点都正常
//下边是官方给出的解决方法，需要全局回调， https://github.com/moxiecode/plupload/issues/1494#issuecomment-317610380
//window.flash_callback_with_unique_name = function (event) {
//  plupload.Uploader.prototype.dispatchEvent(event);
//};
//
//plupload.ua.global_event_dispatcher = 'flash_callback_with_unique_name';

class Main extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      containerId: `${new Date().getTime()}_${Math.ceil(Math.random() * 100000)}`,
        listT: [],
        listB: [],
        overflow: false,
        colspan: 0,
        width: 0,
    }
    this.playImg = this.playImg.bind(this);
  }
  componentDidMount() {
    const { datas = [] ,maxFiles = Infinity, uploadId = '', display = true } = this.props;
    const { containerId } = this.state;
    const cotWidth = $(`#${uploadId}_${containerId}`).width() || 0;
    const emWidth = $(`.excelMainTable`) ? $(`.excelMainTable`).width() : 0;
    const docWidth = $(window).width() || 1;
    const denWidth = emWidth ? emWidth : docWidth;
    const overflow = !(maxFiles - datas.length > 0)
    this.setState({ listT: datas, overflow, colspan: cotWidth / denWidth, width: cotWidth === 0 ? '100%' : cotWidth});
    if(jQuery.browser.msie && parseInt(jQuery.browser.version) < 10){
      display === true && this.initUploader();
    }else{
      this.initUploader();
    }
    $(window).resize(()=>{
      this._reactInternalInstance !== undefined && this.getWidth();
    })
  }
  componentWillReceiveProps(nextProps) {
    let { datas = [], maxFiles = Infinity, uploadUrl = '', limitType = '', maxUploadSize = 0, multiSelection = true, display = true } = this.props,
      nextPropDatas  = nextProps.datas || [],
      nextPropUploadUrl  = nextProps.uploadUrl || '',
      nextPropLimitType  = nextProps.limitType || '',
      nextPropMaxUploadSize  = nextProps.maxUploadSize || 0,
      nextPropMultiSelection  = nextProps.multiSelection !== undefined ? nextProps.multiSelection : true,
      nextPropDisplay  = nextProps.display === false ? nextProps.display : true;

    if(jQuery.browser.msie && parseInt(jQuery.browser.version) < 10 && display === false && nextPropDisplay === true){
      !this.uploader && this.initUploader();
    }
    if(!isEqual(datas,nextPropDatas)){
      const overflow = !(maxFiles - nextPropDatas.length > 0)
      this.setState({listT: nextPropDatas, overflow})
    }
    if(uploadUrl !== nextPropUploadUrl || limitType !== nextPropLimitType || maxUploadSize !== nextPropMaxUploadSize || multiSelection !== nextPropMultiSelection){
      this.resetUploaderOption(nextPropUploadUrl, nextPropLimitType, nextPropMaxUploadSize, nextPropMultiSelection);
    }
  }
  componentDidUpdate() {
    this.uploader && this.uploader.refresh();
  }
  componentWillUnmount() {
    this.uploader && this.uploader.destroy();
    window.startUploadAll = null;
  }
  getWidth(){
    const { uploadId = '' } = this.props;
    const { containerId, colspan } = this.state;
    const cotWidth = $(`#${uploadId}_${containerId}`).width() || 0;
    const emWidth = $(`.excelMainTable`) ? $(`.excelMainTable`).width() : 0;
    const docWidth = $(window).width() || 1;
    const denWidth = emWidth ? emWidth : docWidth;
    let width = denWidth * colspan;
    width = (width === 0 || cotWidth === 0) ? '100%' : (width > cotWidth ? cotWidth : (width > 800 ? 800 : (width < 170 ? 170 : width)));
    this.setState({width});
  }
//  resetItemStyle(){
//    const { uploadId = '' } = this.props;
//    const { containerId, width } = this.state;
//    $(`#container_${uploadId}_${containerId} .wea-upload-list-item-file`).css({width: width + 'px',textOverflow:'ellipsis',whiteSpace: 'nowrap'})
//  }
  resetUploaderOption(uploadUrl, limitType, maxUploadSize, multiSelection){
    const { containerId } = this.state;
    let filters = {
      mime_types : limitType ? [{ title : "limitType", extensions : limitType.indexOf('jpg') >= 0 ? `${limitType},jpeg` : limitType}] : [],
      prevent_duplicates : false  //不允许选取重复文件
    }
    if(maxUploadSize) filters.max_file_size = `${maxUploadSize}mb`; //最大上传大小
    this.uploader && this.uploader.setOption({
      url: uploadUrl,
      filters,
      multi_selection: multiSelection //默认开启多选文件
    })
    this.resetListB();
  }
  initUploader(){
    const {
      uploadId = '',
      uploadUrl = '',
      autoUpload = true,
      limitType = '',
      maxUploadSize = 0,
      multiSelection = true,
    } = this.props;
    const { containerId } = this.state;
    let filters = {
      mime_types : limitType ? [{ title : "limitType", extensions : limitType.indexOf('jpg') >= 0 ? `${limitType},jpeg` : limitType}] : [],
      prevent_duplicates : false  //不允许选取重复文件
    }
    if(maxUploadSize) filters.max_file_size = `${maxUploadSize}mb`; //最大上传大小
    this.uploader = new window.plupload.Uploader({
      container:  `container_${uploadId}_${containerId}`,
      browse_button: `browsebtn_${uploadId}_${containerId}`,
      runtimes: jQuery.browser.msie && parseInt(jQuery.browser.version) < 10 ? 'flash' : 'html5,flash,html4',
      //runtimes: 'flash',
      multipart: true, // multipart/form-data的形式来上传文件
      chunk_size: '0', //分片上传大小
      url: uploadUrl,
      flash_swf_url: '/cloudstore/resource/pc/plupload-2.3.1/js/Moxie.swf',
      filters,
      multi_selection: multiSelection //默认开启多选文件
    });
    //初始化
    this.uploader.init();
    //绑定主要事件,state同步

    //const uploadEvents = [
    //  'PostInit', 'Browse', 'Refresh', 'StateChanged', 'QueueChanged', 'OptionChanged',
    //  'BeforeUpload', 'UploadProgress', 'FileFiltered', 'FilesAdded', 'FilesRemoved', 'FileUploaded', 'ChunkUploaded',
    //  'UploadComplete', 'Destroy', 'Error'
    //];


    //新增上传
    this.uploader.bind('FilesAdded', (up, files) => {
      const { listT, listB } = this.state;
      let newListB = listB.concat(files);
      newListB = newListB.map(file => {
        let newFile = {...file};
        newFile.progress = 10;
        if(autoUpload) newFile.showProgress = true;
        return newFile;
      })
      this.setState({listB: newListB});
      if(autoUpload){
        this.doUpload();
      }else{
          typeof this.props.onUploading === 'function' && this.props.onUploading('false')
      }
    });
    //删除文件
    this.uploader.bind('FilesRemoved', (up, rmFiles) => {
      const { listT, listB } = this.state;
          let newListB = [].concat(listB);
          rmFiles.map(rf => {
            newListB = newListB.filter(file => rf.id !== file.id)
          });
      this.setState({listB: newListB});
    });

    //抛错
    this.uploader.bind('Error', (up, err) => {
      if(err.code === -500){
        console && console.error('上传组件初始化出错!');
      }else if(err.code === -702){
        message.error('文件大小超出组件所能处理的最大值，请重新上传!',3);
      }else if(err.code === -600){
        message.error('上传文件超出限制大小，请重新上传!',3);
      }else if(err.code === -601){
        message.error('上传文件类型错误，请重新上传!',3);
      }else if(err.code === -602){
        message.error('上传文件重复，请重新上传!',3);
      }else{
        //message.error('上传组件出错，请联系管理员!',3);
        //console && console.error('上传组件出错，请联系管理员!');
      }
      if(err.file){
        const { listB } = this.state;
        let newListB = [].concat(listB);
        if(err.code === -600){
          err.file.error = '文件过大'
        }else if(err.code === -601){
          err.file.error = '类型错误'
        }
        if(autoUpload) {
          //err.file.progress = 10;
          err.file.progressStatus = 'exception';
          err.file.showProgress = true;
        }
        newListB.push(err.file);
        this.setState({listB: newListB});
        setTimeout(() => {
          const stlistB = this.state.listB;
          let stNewListB = [].concat(stlistB);
          stNewListB = stNewListB.filter(file => !file.error)
          this.setState({listB: stNewListB});
        },2000);
      }
    });
    //上传进度
    this.uploader.bind('UploadProgress', (up, pgFile) => {
      const { listT, listB } = this.state;
      let newListB = [].concat(listB);
      newListB = newListB.map(file => {
        if(pgFile.id == file.id) {
          let newFile = {...file};
          if(newFile.progress < 90 ){
            newFile.progress += 10;
          }else{
            newFile.progress = 90;
          }
          return newFile
        }else{
          return file
        }
      })
      this.setState({listB: newListB});
    });
    //分片上传完成
    //this.uploader.bind('ChunkUploaded', (up, ckFile, res) => {
    //  console.log('分片上传完成 ChunkUploaded: ', ckFile, res)
    //});
    //某个文件上传完
    this.uploader.bind('FileUploaded', (up, upFile, res) => {
      let upError = res.status !== 200 || !res.response || (res.response && ((JSON.parse(res.response).stauts === (false || 'false')) || !JSON.parse(res.response).data));
      if(upError){
        const { listB } = this.state;
      let newListB = [].concat(listB);
      newListB = newListB.map(file => {
          if(upFile.id === file.id){
            let newFile = {...file};
            newFile.error = res.response && JSON.parse(res.response).msg ? JSON.parse(res.response).msg : '上传服务器失败';
          newFile.progressStatus = 'exception';
          newFile.showProgress = true;
          message.error(`${newFile.name} ${newFile.error}`,3);
            return newFile;
          }else{
          return file
        }
        });
      this.setState({listB: newListB});
      typeof this.props.onUploading === 'function' && this.props.onUploading('error');
      }else{
        const { listT, listB } = this.state;
          let newListB = [].concat(listB);
        newListB = newListB.map(file => {
          if(upFile.id === file.id){
            let newFile = {...file, ...JSON.parse(res.response).data};
            newFile.progress = 100;
            return newFile;
          }else{
          return file
        }
        });
        this.setState({listB: newListB});
      }
    });
    //全部文件上传完成
    this.uploader.bind('UploadComplete', (up, upFiles) => {
      setTimeout(()=>{
        const { listT, listB } = this.state;
        let find = false;
        listB.map(file => {
          if(file.error) find = true
        });
        if(find) {
          setTimeout(() => {
            const nowListT = this.state.listT;
            const nowListB = this.state.listB;
            let newListB = [].concat(nowListB);
            newListB = newListB.filter(file => !file.error);
            let newListT = nowListT.concat(newListB);
            this.onChange(newListT, newListB);
          this.setState({listT: newListT, listB: []});
            typeof this.props.onUploading === 'function' && this.props.onUploading('uploaded');
        },2000);
        }else{
          let newListT = listT.concat(listB);
          this.onChange(newListT, listB);
            this.setState({listT: newListT, listB: []});
          typeof this.props.onUploading === 'function' && this.props.onUploading('uploaded');
        }
      },200);
    });
    //全局调用
    if(!autoUpload){
      let startUploadAllOld;
      if(typeof window.startUploadAll === 'function'){
        startUploadAllOld = window.startUploadAll
      }
      window.startUploadAll = () => {
        const { listT, listB } = this.state;
        if(listB.length > 0){
        let newListB = [].concat(listB);
        newListB = newListB.map(file => {
          let newFile = {...file};
          newFile.progress = 10;
          newFile.showProgress = true;
          return newFile;
        })
        this.setState({listB: newListB});
          this.doUpload();
        }
        typeof startUploadAllOld === 'function' && startUploadAllOld();
      }
    }
    //flash 遮罩无法 hover 问题
    this.uploader.bind('Init', () => {
      if(jQuery.browser.msie && parseInt(jQuery.browser.version) < 10){
        $(`#container_${uploadId}_${containerId}>div.moxie-shim-flash`).hover(()=>{
          $(`button#browsebtn_${uploadId}_${containerId}`).css({
            color: '#57c5f7',
            borderColor: '#57c5f7',
          })
          $(`i#browsebtn_${uploadId}_${containerId}`).css({
            color: '#289cff'
          })
        },()=>{
          $(`button#browsebtn_${uploadId}_${containerId}`).css({
            color: '#000',
            borderColor: '#d9d9d9',
          })
          $(`i#browsebtn_${uploadId}_${containerId}`).css({
            color: '#a8a8a8'
          })
        })
        }
    })
  }
  doUpload() {
    typeof this.props.onUploading === 'function' && this.props.onUploading('uploading')
    this.uploader && this.uploader.start();
  }
  resetListB(){
    const { viewAttr = 2 } = this.props;
    const { listT, listB } = this.state;
    listB.map(file => {
      this.uploader && this.uploader.removeFile(file.id);
    });
    this.setState({listB: []})
    const required = viewAttr == 3 && listT.length == 0;
    typeof this.props.onUploading === 'function' && this.props.onUploading(required ? 'true' : 'false')
  }
  clearAllFiles() {
    //仅删除下部的，批量上传有效
    confirm({
      title: '确定要删除所有吗？',
      content: '',
      onOk: () => {
        const { viewAttr = 2 } = this.props;
        const { listT, listB } = this.state;
        listB.map(file => {
          this.uploader && this.uploader.removeFile(file.id);
        });
        this.setState({listB: []})
        const required = viewAttr == 3 && listT.length == 0;
        typeof this.props.onUploading === 'function' && this.props.onUploading(required ? 'true' : 'false')
      }
    });
  }
  doDeleteT(fileid){
    //删除上部的，自动上传需调用onchange
    const { autoUpload = true, viewAttr = 2 } = this.props;
    const { listT, listB } = this.state;
    let newListT = [].concat(listT);
    let title = '';
      newListT.map(file => {
        if(fileid == file.fileid){
          title = file.filename
        }
      })
    newListT = newListT.filter(file => fileid !== file.fileid);
      confirm({
        title: `确定要删除${title}吗？`,
        content: '',
        onOk: () => {
          this.setState({listT: newListT});
          if(autoUpload){
            this.onChange(newListT, listB);
          }else{
            this.onChange(newListT, []);
            const required = viewAttr == 3 && newListT.length == 0 && listB.length == 0;
            typeof this.props.onUploading === 'function' && this.props.onUploading(required ? 'true' : 'false')
          }
        }
    });
  }
  doDeleteB(id){
    //仅删除下部的，批量上传有效
    const { viewAttr = 2 } = this.props;
    const { listT, listB } = this.state;
    let newListB = [].concat(listB);
    let title = '';
    newListB.map(file => {
      if(id == file.id){
        title = file.name
      }
    })
    newListB = newListB.filter(file => id !== file.id);
      confirm({
        title: `确定要删除${title}吗？`,
        content: '',
        onOk: () => {
          this.uploader && this.uploader.removeFile(id);
          this.setState({listB: newListB});
          const required = viewAttr == 3 && listT.length == 0 && newListB.length == 0;
          typeof this.props.onUploading === 'function' && this.props.onUploading(required ? 'true' : 'false')
        }
    });
  }
  onChange(listT,listB){
    let list = [];
    listT.map(t => {
      const { fileExtendName, fileid, filelink, filename, filesize, imgSrc, loadlink, showLoad, showDelete, isImg } = t;
      list.push({ fileExtendName, fileid, filelink, filename, filesize, imgSrc, loadlink, showLoad, showDelete, isImg });
    });
    let ids = listT.map(t => t.fileid);
    if(typeof this.props.onChange === 'function'){
      this.props.onChange(ids,list);
    }
  }
  render() {
    const {
      uploadId = '',
      uploadUrl = '',
      category='',
      viewAttr = 2,
      showBatchLoad = false,
      value = '',
      maxUploadSize = 0,
      btnSize = 'default',
      batchLoadUrl = '',
      showClearAll = true,
      errorMsg = '',
      style = {},
      children,
      listType = 'list',
      RenderList = '',
    } = this.props;
    const { listT, listB, containerId } = this.state;
    const disabled = uploadUrl == '' || viewAttr == 1 || category === '';
    const required = viewAttr == 3 && listB.length == 0 && listT.length == 0;
    const notShow = errorMsg !== '' || uploadUrl == '' || category == '';
    let btn = null;
    if(children){
      btn = notShow ? <span onClick={e =>{
        message.error(uploadUrl == '' && viewAttr !== 1 ? '请设置文件上传服务器地址!' : (category == '' && viewAttr !== 1 ? '请设置文件上传目录!' : ''),500);
        e.stopPropagation && e.stopPropagation();
      e.preventDefault && e.preventDefault();
      e.nativeEvent && e.nativeEvent.preventDefault();
      }} >{children}</span> : children
    }
    let listNull = listT.length == 0 && listB.length == 0;
    const cls = classNames({
      'wea-field': /^field/.test(this.props.fieldName),
    });
    return (
      <div className={`wea-upload ${cls}`} id={`${uploadId}_${containerId}`} style={style}>
      	{ RenderList ? <RenderList datas={{listT, listB}} /> : '' }
        {children ?
          <div id={`container_${uploadId}_${containerId}`} className='wea-upload-container' >
            <span id={`browsebtn_${uploadId}_${containerId}`} title='上传附件' style={{ display: 'inline-block'}}>
              { btn }
            </span>
            <input type='hidden' name={uploadId} id={uploadId} value={value} />
          </div>
        :
          <span>
            <div>
              {this.renderlistT()}
              {
                errorMsg !== '' ? <span style={{color: '#f00'}} >{errorMsg}</span> :
                (
                  uploadUrl == '' && viewAttr !== 1 ? <span style={{color: '#f00'}} >请设置文件上传服务器地址!</span> :
                  (
                    category == '' && viewAttr !== 1 ? <span style={{color: '#f00'}} >请设置文件上传目录!</span> : ''
                  )
                )
              }
              <div className='wea-upload-container' style={notShow ? { display: 'inline-block', width: 0, height: 0, overflow: 'hidden'} : {}}>
                { btnSize === 'small' ?
                  <span style={{display: 'inline-block', verticalAlign: 'middle'}}>
                    <span id={`container_${uploadId}_${containerId}`} style={viewAttr === 1 ? { display: 'inline-block', width: 0, height: 0, overflow: 'hidden'} : {}}>
                      <i id={`browsebtn_${uploadId}_${containerId}`} className='icon-coms-AddTo wea-upload-icon' title='上传附件' style={{ margin: '0 5px 5px 0'}}/>
                      { showClearAll && !listNull &&
                        <Button type="ghost" disabled={listB.length == 0} shape="circle-outline" icon="cross" title='清除所有' style={{margin:'0 5px 5px 0'}} onClick={this.clearAllFiles.bind(this)}/>
                      }
                    </span>
                      { showBatchLoad && !listNull &&
                      <Button type="ghost" shape="circle-outline" icon="download" title='全部下载' style={{margin:'0 5px 5px 0'}} onClick={this.download.bind(this,batchLoadUrl)}/>
                      }
                  </span>
                  :
                  <span>
                    <span id={`container_${uploadId}_${containerId}`} style={viewAttr === 1 ? { display: 'inline-block', width: 0, height: 0, overflow: 'hidden'}  : {} }>
                      <Button disabled={disabled} type="ghost" id={`browsebtn_${uploadId}_${containerId}`} style={{margin: '0 5px 5px 0'}}>
                          <Icon type="upload" /> 上传附件
                        </Button>
                      { showClearAll &&
                          <Button disabled={listB.length == 0} type="ghost" style={{margin:'0 5px 5px 0'}} onClick={this.clearAllFiles.bind(this)}>
                            <Icon type="cross" /> 清除所有
                          </Button>
                      }
                    </span>
                      { showBatchLoad && !listNull &&
                        <Button type="ghost" style={{margin:'0 5px 5px 0'}} onClick={this.download.bind(this,batchLoadUrl)}>
                          <Icon type="download" /> 全部下载
                        </Button>
                      }
                    </span>
                  }
                <span style={{display:'inline-block', marginBottom: 5}}>
                  { viewAttr !== 1 && !!maxUploadSize && <span style={{margin:'4px 5px 0 0',verticalAlign: 'top'}}> 最大{maxUploadSize}M/个</span>}
                  { required &&
                  <span className="wea-required-e9" id={`${this.props.fieldName}span`}>
                      <img src="/images/BacoError_wev9.png" align="middle"/>
                  </span> }
                </span>
              </div>
              {this.renderlistB()}
              <input type='hidden' name={uploadId} id={uploadId} value={value} />
              <iframe ref={`download_${uploadId}_${containerId}`} style={{display: 'none'}} />
            </div>
          </span>
        }
      </div>
    )
  }
  renderlistT(){
    const { listType = 'list', viewAttr = 2, imgHeight = 50, imgWidth = 50, autoUpload = true } = this.props;
    const { listT, width } = this.state;
    return (
      <div className='wea-upload-list' style={{padding: listT.length > 0 ? '0 0 5px 0' : 0}}>
        {
          listT.map(d => {
            const { fileid, imgSrc, filelink, filename, filesize, loadlink, showLoad, showDelete, isImg } = d;
            let imgBtnMagrinLeft = (imgWidth && imgWidth > 90 ? (imgWidth + 10) : 100)/4 - 8;
            let imgBtnMagrinRight = (imgWidth && imgWidth > 90 ? (imgWidth + 10) : 100)/4 - 5;
            const itemOpsDivWidth  = ((viewAttr !== 1 && showDelete) || showLoad) ? "64px":"0px";
            const imgDom = autoUpload ?
              <div className='wea-upload-imgs-item wea-upload-imgs-item-h' style={{width,minWidth:imgWidth + 70,height:imgHeight + 10}}>
                <img className='formImgPlay' src={imgSrc} onClick={this.playImg} data-imgsrc={loadlink} style={{width: imgWidth, height: imgHeight, cursor: 'pointer'}} />
                <span style={{position: 'absolute',right: 0,top:5,width: 60,lineHeight: `${imgHeight}px`}}>
                  { viewAttr !== 1 && showDelete && <Icon type="cross" title='删除' style={{float:'right',cursor:'pointer',fontSize:10,marginTop: imgHeight/2 - 5,marginRight: 10 }} onClick={this.doDeleteT.bind(this,fileid)}/>}
                  { showLoad && <i className='icon-coms-download wea-upload-icon' title='下载' style={{float:'right',fontSize:16,marginTop: imgHeight/2 - 8,marginRight: 10}} onClick={this.download.bind(this,loadlink)}/> }
                </span>
              </div>
              :
              <div className='wea-upload-imgs-item wea-upload-imgs-item-v' style={{width: (imgWidth && imgWidth > 90 ? (imgWidth + 10) : 100)}}>
                <img className='formImgPlay' src={imgSrc} onClick={this.playImg} data-imgsrc={loadlink} style={{width: imgWidth, height: imgHeight, cursor: 'pointer'}} />
                <p className='wea-upload-imgs-item-v-ops' style={{textAlign: showLoad === (viewAttr !== 1 && showDelete) ? 'left' : 'center' }}>
                  { showLoad && <i className='icon-coms-download wea-upload-icon' title='下载' style={{marginLeft: (viewAttr !== 1 && showDelete) ? imgBtnMagrinLeft : 0}} onClick={this.download.bind(this,loadlink)}/> }
                  { viewAttr !== 1 && showDelete && <Icon type="cross" title='删除' style={showLoad ? {float:'right',marginTop:6,fontSize:10,cursor:'pointer',marginRight: imgBtnMagrinRight} : {marginTop:6,fontSize:10,cursor:'pointer'}} onClick={this.doDeleteT.bind(this,fileid)}/>}
                </p>
              </div>;
            return (
              listType == 'img' ? imgDom :
                <div className='wea-upload-list-item'>
                  <div className={`wea-upload-list-item-file wea-upload-list-item-file-t${autoUpload ? '-nosize' : ''}`} style={{width}}>
                    <img src={imgSrc} style={{width:16,height:16}} />
                    {
                      isImg ?
                      <a href='javascript:void(0);' title={filename} onClick={this.playImg} className='formImgPlay wea-field-link' src={filelink} data-imgsrc={loadlink}>{filename}</a>
                      :
                      <a href='javascript:void(0);' title={filename} onClick={this.open.bind(this, filelink)} className='wea-field-link'>{filename}</a>
                    }
                    {!autoUpload &&
                      <div className='wea-upload-list-item-filesize'>
                        <span style={{color:'#999',marginLeft:8}}>{filesize}</span>
                      </div>
                    }
                    <div className='wea-upload-list-item-ops' style={{width:itemOpsDivWidth}}>
                      { viewAttr !== 1 && showDelete && <Icon type="cross" title='删除' style={{float:'right',margin:'9px 10px 0 5px',cursor:'pointer',fontSize:10}} onClick={this.doDeleteT.bind(this,fileid)}/>}
                      { showLoad && <i className='icon-coms-download wea-upload-icon' title='下载' style={{float:'right',margin:'6px 5px 0 5px'}} onClick={this.download.bind(this,loadlink)}/>}
                    </div>
                  </div>
                </div>
            )
          })
        }
      </div>
    )
  }
  renderlistB(){
    const { autoUpload = true } = this.props;
    const { listB, width } = this.state;
    return (
      <div className='wea-upload-list' style={{padding: listB.length > 0 ? '0 0 5px 0' : 0}}>
        {
          listB.map(d => {
            const { name, id, progress, showProgress, error, progressStatus } = d;
            let status = error && progressStatus ? {status: progressStatus} : {};
            return (
              <div className='wea-upload-list-item'>
                <div className='wea-upload-list-item-file wea-upload-list-item-file-b' style={error ? {width, padding: '0 110px 0 0'} : {width}}>
                  {!autoUpload && <Icon type="paper-clip" style={{marginRight:5}}/>}
                  {name}
                  {error && <span style={{display: 'inline-block', color: '#f00', position: 'absolute', right: 40, top: 0}}>{`（${error}）`}</span>}
                  <Icon type="cross" className='wea-upload-list-item-del' style={{fontSize:10}} title='删除' onClick={this.doDeleteB.bind(this,id)}/>
                </div>
                {showProgress && <Progress style={{width}} percent={progress} strokeWidth={3} {...status}/>}
              </div>
            )
          })
        }
      </div>
    )
  }
  playImg(e){     //图片轮播
    let imgPool = [];
    let indexNum = 0;
    jQuery(".formImgPlay").each(function(){
      imgPool.push(jQuery(this).attr('data-imgsrc'));
    });
    for(let i = 0; i < imgPool.length ; i ++){
      if(jQuery(e.target).attr('data-imgsrc') == imgPool[i]){
        break;
      }else{
        indexNum++;
      }
    }
    //console.log("imgPool--",imgPool,"indexNum--",indexNum);
    IMCarousel.showImgScanner4Pool(true, imgPool, indexNum, null, window.top);
  }
  download(downloadURL){
    const { uploadId = ''} = this.props;
    const { containerId = ''} = this.state;
    this.refs[`download_${uploadId}_${containerId}`].src = '';
    this.refs[`download_${uploadId}_${containerId}`].src = downloadURL;
  }
  open(url){
    openFullWindowHaveBar(url);
  }
}

export default Main;

